package nettyProtocol.wather;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import nettyProtocol.pojo.Header;
import nettyProtocol.pojo.NettyMessage;
import nettyProtocol.handshakeAndAuthentication.MessageType;

public class HeartBeatRespHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        NettyMessage message = (NettyMessage) msg;
        //返回心跳应答消息
        if(message.getHeader() != null && message.getHeader().getType() == MessageType.HEART_REQ.value){
            System.out.println("Receive client heart beat message : -->" + message);
            NettyMessage heartBeat = buildHeatBeat();
            System.out.println("Send heart beat response message to client -->" + heartBeat);
            ctx.writeAndFlush(heartBeat);
        } else {
            System.out.println("传入user自定义链路");
            ctx.fireChannelRead(msg);
        }

    }

    private NettyMessage buildHeatBeat() {
        NettyMessage message = new NettyMessage();
        Header header = new Header();
        header.setType(MessageType.HEART_RESP.value);
        message.setHeader(header);
        return message;
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }
}
